<template>
  <div id="app">
    <div class="chat-container">
      <div class="chat-box" ref="chatBox">
        <div v-for="message in messages" :key="message.id" class="message">
          <div :class="message.sender === 'user' ? 'user-message' : 'bot-message'">
            <template v-if="message.sender === 'assistant'">
              <p v-text="message.text"></p>
            </template>
            <template v-else>
              <p v-text="message.text"></p>
            </template>
          </div>
        </div>
      </div>
      <div v-if="loading" class="loading-spinner">
        <div class="spinner"></div>
        <p class="loading-text">正在思考...</p>
      </div>
      <div class="input-container">
        <input
          v-model="userMessage"
          @keyup.enter="sendMessage"
          class="chat-input"
          type="text"
          :disabled="loading"
          placeholder="输入一条消息..."
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, nextTick } from 'vue';
  import axios from 'axios';

  // 定义消息类型
  interface Message {
    id: number;
    sender: 'user' | 'assistant';
    text: string;
  }

  // 定义传参格式
  interface ChatRequest {
    role: string;
    content: string;
  }

  // 数据绑定
  const userMessage = ref<string>('');
  const messages = ref<Message[]>([]);
  const chatBox = ref<HTMLDivElement | null>(null);
  const chatRequests = ref<ChatRequest[]>([]);
  const loading = ref<boolean>(false);

  // 获取当前时间
  const getCurrentTime = (): string => {
    return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };

  // 发送消息
  const sendMessage = async () => {
    if (userMessage.value.trim() === '') return;

    // 添加用户消息到聊天框
    const userMsg: Message = {
      id: Date.now(),
      sender: 'user',
      text: userMessage.value,
    };
    messages.value.push(userMsg);

    // 添加到 API 请求历史
    const userMsgRequest: ChatRequest = {
      role: 'user',
      content: userMessage.value,
    };
    chatRequests.value.push(userMsgRequest);

    // 滚动到底部
    await nextTick();
    chatBox.value?.scrollTo({ top: chatBox.value.scrollHeight, behavior: 'smooth' });

    loading.value = true; // 显示加载动画
    userMessage.value = ''; // 清空输入框

    try {
      const response = await axios.post(
        'https://api.hunyuan.cloud.tencent.com/v1/chat/completions',
        {
          model: 'hunyuan-turbo',
          messages: chatRequests.value,
          enable_enhancement: true,
        },
        {
          headers: {
            Authorization: 'Bearer sk-oNxG9sdorb2nBSV7x4VZXdr3ynExTi93ACALb7iGiIXU2ZzC',
            'Content-Type': 'application/json',
          },
        },
      );

      // 获取 API 响应内容
      const assistantReply = response.data.choices[0].message.content;

      // 添加 AI 回复到聊天框
      messages.value.push({
        id: Date.now() + 1,
        sender: 'assistant',
        text: assistantReply,
      });

      // 记录 AI 回复历史
      chatRequests.value.push({
        role: 'assistant',
        content: assistantReply,
      });

      // 滚动到底部
      await nextTick();
      chatBox.value?.scrollTo({ top: chatBox.value.scrollHeight, behavior: 'smooth' });
    } catch (error) {
      console.error('Error sending message:', error);
      messages.value.push({
        id: Date.now() + 2,
        sender: 'assistant',
        text: '抱歉，出现了一个错误。',
      });
    } finally {
      loading.value = false; // 隐藏加载动画
    }
  };
</script>

<style scoped>
  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  /* 整体布局 */
  html,
  body {
    height: 100%;
    margin: 0;
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
  }

  /* 聊天容器 */
  .chat-container {
    width: 100%;
    max-width: 1200px;
    height: 800px;
    margin: 0 auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
    overflow: hidden;
  }

  /* 聊天框 */
  .chat-box {
    flex-grow: 1;
    overflow-y: auto;
    padding: 10px;
    padding-bottom: 60px;
  }

  /* 消息 */
  .message {
    margin-bottom: 16px;
    display: flex;
    justify-content: flex-start;
    max-width: 100%;
  }

  /* 用户消息 */
  .user-message {
    background-color: #4caf50;
    padding: 10px 15px;
    border-radius: 15px;
    color: white;
    word-wrap: break-word;
    max-width: 80%;
    margin-left: auto;
    align-self: flex-end;
    position: relative;
  }

  /* 机器人消息 */
  .bot-message {
    background-color: #e0e0e0;
    padding: 10px 15px;
    border-radius: 15px;
    color: #333;
    word-wrap: break-word;
    max-width: 80%;
    align-self: flex-start;
  }

  /* 输入框容器 */
  .input-container {
    position: relative;
    padding-top: 10px;
  }

  /* 输入框 */
  .chat-input {
    width: 100%;
    padding: 12px 16px;
    border-radius: 25px;
    border: 1px solid #ccc;
    font-size: 16px;
    outline: none;
  }

  /* 输入框聚焦时边框变色 */
  .chat-input:focus {
    border-color: #4caf50;
  }

  /* 加载动画 */
  .loading-spinner {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 100;
  }

  .spinner {
    border: 4px solid rgb(0 0 0 / 10%);
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
  }

  .loading-text {
    margin-top: 10px;
    font-size: 14px;
    color: #3498db;
    font-weight: bold;
  }
</style>
